package com.jackrain.nea.wms.mq;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.impl.util.MsgConvertUtil;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.wms.service.BaseProcess;
import lombok.extern.slf4j.Slf4j;
import java.io.Serializable;
import static com.aliyun.openservices.ons.api.Action.CommitMessage;

/**
 * @author zc
 * @date 2017/5/23
 */
@Slf4j
public class MQMessageListener implements MessageListener {
    @Override
    public Action consume(Message message, ConsumeContext context) {

        try {
            System.out.println("consume");
            log.debug("consume");
            mqConsume(message, context);
            return CommitMessage;
        } catch (Exception e) {
            e.printStackTrace();
//            //ons问题得重新消费并发送
//            if ((e instanceof ONSClientException)) {
                return CommitMessage;
//            }

//            String tag = message.getTag();
//            String adOrgTag = "ViewAdOrgService";
//            String adUserTag = "ViewAdUserService";
//            String adPasswordServiceTag = "ViewAdPasswordService";
//            String adOrgStoreServiceTag = "ViewAdOrgStoreService";

//            if ("ViewRetailPostService".equals(tag) || "ViewRetailChargePostService".equals(tag)) {
//                return CommitMessage;
//            } else {
//                return ReconsumeLater;
//            }

        }

    }

    public ValueHolder mqConsume(Message message, ConsumeContext context) throws Exception {

        ValueHolder valueHolder = null;

        if (message == null) {
            log.error("message is null");
            return valueHolder;
        }


        Serializable ser = MsgConvertUtil.objectDeserialize(message.getBody());

//        log.debug("mqConsume ser:" + ser.toString());

        if (ser instanceof JSONObject) {
            JSONObject paramObject = JSONObject.parseObject(ser.toString());
            log.debug("paramObject:" + paramObject.toJSONString());
            log.debug("tag:" + message.getTag());
            String beanName = "com.jackrain.fc.service." + message.getTag();
            BaseProcess baseProcess = (BaseProcess) ApplicationContextHandle.getBean(beanName);
            valueHolder = baseProcess.process(paramObject, message);
        } else {
            log.error("message body 格式错误");
            throw new NDSException("message body 格式错误");
        }

        return valueHolder;


    }
}
